package com.polaris.live.utils.sensor.base

import androidx.appcompat.app.AppCompatActivity
import com.polaris.live.interface_bag.XpopupCallBackImpl
import com.polaris.live.popup.BottomButtonPopup
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView

/**
 * 弹窗模块
 *
 * @author Created by lucas on 2023/10/25 16:10
 * @since 1.0.0
 */
abstract class DialogModule(
    context: AppCompatActivity,
    l: OnEnabledModuleListener? = null
) : AbstractModule(context, l) {

    private val mModules: Array<IModule>
    private var isShowDialog = true
    private var mOnDismissListener: OnDismissListener? = null

    init {
        mModules = createModules()
        check(mModules.isNotEmpty()) { "IModule must exist" }
    }

    protected abstract fun createModules(): Array<IModule>

    override fun runModule() {
        val builder = BottomButtonPopup.Builder(mContext, title)
        mModules.forEach { module ->
            val childTitle = if (module is DialogModule) {
                module.title + " >>"
            } else {
                module.title
            }

            builder.addButton(childTitle) {
                module.runModule()
                it.dismiss()
            }
        }
        builder.setNegativeListener { it.dismiss() }

        XPopup.Builder(mContext)
            .isDestroyOnDismiss(true)
            .setPopupCallback(object : XpopupCallBackImpl {
                override fun onDismiss(popupView: BasePopupView) {
                    mOnDismissListener?.onDismiss(popupView)
                }
            })
            .asCustom(builder.build())
            .show()
    }

    fun setOnDismissListener(l: OnDismissListener) {
        mOnDismissListener = l
    }

    fun isShowDialog(): Boolean {
        return isShowDialog
    }
}

fun interface OnDismissListener {

    fun onDismiss(popup: BasePopupView)

}